package com.x.xiaoshuo.ui.read;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.x.mvp.base.view.activity.ActivityView;
import com.x.mvp.utils.DensityUtil;
import com.x.service.entity.BookDetail;
import com.x.service.entity.BookListsBean;
import com.x.service.entity.Chapter;
import com.x.service.entity.ChapterList;
import com.x.xiaoshuo.Constant;
import com.x.xiaoshuo.R;
import com.x.xiaoshuo.di.XActivityComponent;
import com.x.xiaoshuo.entity.DownloadQueue;
import com.x.xiaoshuo.manager.CacheManager;
import com.x.xiaoshuo.manager.CollectionsManager;
import com.x.xiaoshuo.manager.SettingManager;
import com.x.xiaoshuo.manager.ThemeManager;
import com.x.xiaoshuo.service.DownloadBookService;
import com.x.xiaoshuo.ui.dialog.ChapterDialog;
import com.x.xiaoshuo.utils.BuiduUtils;
import com.x.xiaoshuo.utils.FileUtils;
import com.x.xiaoshuo.utils.ScreenUtils;
import com.x.xiaoshuo.utils.SharedPreferencesUtil;
import com.x.xiaoshuo.widget.readview.OnReadStateChangeListener;
import com.x.xiaoshuo.widget.readview.aim.ReadView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import timber.log.Timber;


public class ReadActivity extends ActivityView<ReadPresenter> {
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    private Receiver receiver = new Receiver();
    ImageView mIvBack;
    FrameLayout flReadWidget;
    FrameLayout expressAdContainerStart;
    FrameLayout expressAdContainerEndS;
    FrameLayout expressAdContainerEnd;
    LinearLayout mLlBookReadTop;
    ImageView autoRead;
    TextView mTvBookReadTocTitle;
    CheckBox settingNight;
    LinearLayout chapterSelect;
    SeekBar seekbarChapter;
    TextView preChapter;
    TextView nextChapter;
    TextView mTvBookReadSettings;
    TextView mTvBookReadDownload;
    TextView mTvBookReadToc;
    LinearLayout mLlBookReadBottom;
    RelativeLayout mRlBookReadRoot;
    TextView mTvDownloadProgress;
    TextView tvBookReadLD;
    LinearLayout rlReadAaSet;
    LinearLayout bgContainter;
    CheckBox h1;
    CheckBox h2;
    CheckBox h3;
    CheckBox h4;
    CheckBox animFlipckCb;
    TextView animFlipck;
    CheckBox animPYCb;
    TextView animPY;
    CheckBox animFZCb;
    TextView animFZ;
    TextView aaMinor;
    TextView aaPlus;
    CheckBox vSreenCb;
    TextView vSreen;
    CheckBox hSreenCb;
    TextView hSreen;
    LinearLayout rlReadBrightness;
    SeekBar brightnessBar;
    CheckBox followSys;
    CheckBox savePowCb;
    TextView savePow;

    private void bindView() {

        expressAdContainerEnd = findViewById(R.id.expressAdContainerEnd);
        expressAdContainerEndS = findViewById(R.id.expressAdContainerEndS);
        expressAdContainerStart = findViewById(R.id.expressAdContainerStart);
        flReadWidget = findViewById(R.id.flReadWidget);
        mIvBack = findViewById(R.id.ivBack);

        nextChapter = findViewById(R.id.nextChapter);
        preChapter = findViewById(R.id.preChapter);
        seekbarChapter = findViewById(R.id.seekbarChapter);
        chapterSelect = findViewById(R.id.chapterSelect);
        settingNight = findViewById(R.id.settingNight);
        mTvBookReadTocTitle = findViewById(R.id.tvBookReadTocTitle);
        autoRead = findViewById(R.id.autoRead);
        mLlBookReadTop = findViewById(R.id.llBookReadTop);

        rlReadAaSet = findViewById(R.id.rlReadAaSet);
        tvBookReadLD = findViewById(R.id.tvBookReadLD);
        mTvDownloadProgress = findViewById(R.id.tvDownloadProgress);
        mRlBookReadRoot = findViewById(R.id.rlBookReadRoot);
        mLlBookReadBottom = findViewById(R.id.llBookReadBottom);
        mTvBookReadToc = findViewById(R.id.tvBookReadToc);
        mTvBookReadDownload = findViewById(R.id.tvBookReadDownload);
        mTvBookReadSettings = findViewById(R.id.tvBookReadSettings);

        mTvBookReadSettings.setOnClickListener(onClickListener);
        mTvBookReadDownload.setOnClickListener(onClickListener);
        mTvBookReadToc.setOnClickListener(onClickListener);
        mLlBookReadBottom.setOnClickListener(onClickListener);
        mRlBookReadRoot.setOnClickListener(onClickListener);
        mTvDownloadProgress.setOnClickListener(onClickListener);
        tvBookReadLD.setOnClickListener(onClickListener);
        rlReadAaSet.setOnClickListener(onClickListener);
        mLlBookReadTop.setOnClickListener(onClickListener);
        autoRead.setOnClickListener(onClickListener);
        mTvBookReadTocTitle.setOnClickListener(onClickListener);
        settingNight.setOnClickListener(onClickListener);
        chapterSelect.setOnClickListener(onClickListener);
//        seekbarChapter.setOnClickListener(onClickListener);
        preChapter.setOnClickListener(onClickListener);
        nextChapter.setOnClickListener(onClickListener);
        mIvBack.setOnClickListener(onClickListener);
        flReadWidget.setOnClickListener(onClickListener);
        expressAdContainerStart.setOnClickListener(onClickListener);
        expressAdContainerEndS.setOnClickListener(onClickListener);
        expressAdContainerEnd.setOnClickListener(onClickListener);


        savePow = findViewById(R.id.savePow);
        bgContainter = findViewById(R.id.bgContainter);
        savePowCb = findViewById(R.id.savePowCb);
        followSys = findViewById(R.id.followSys);
        brightnessBar = findViewById(R.id.brightnessBar);
        rlReadBrightness = findViewById(R.id.rlReadBrightness);
        hSreen = findViewById(R.id.hSreen);
        hSreenCb = findViewById(R.id.hSreenCb);
        vSreen = findViewById(R.id.vSreen);
        vSreenCb = findViewById(R.id.vSreenCb);
        aaPlus = findViewById(R.id.aaPlus);
        aaMinor = findViewById(R.id.aaMinor);
        animFZ = findViewById(R.id.animFZ);
        animFZCb = findViewById(R.id.animFZCb);
        animPY = findViewById(R.id.animPY);
        animPYCb = findViewById(R.id.animPYCb);
        animFlipck = findViewById(R.id.animFlipck);
        animFlipckCb = findViewById(R.id.animFlipckCb);
        h4 = findViewById(R.id.h4);
        h3 = findViewById(R.id.h3);
        h2 = findViewById(R.id.h2);
        h1 = findViewById(R.id.h1);



        h1.setOnClickListener(onClickListener);
        h2.setOnClickListener(onClickListener);
        h3.setOnClickListener(onClickListener);
        h4.setOnClickListener(onClickListener);

        animFlipckCb.setOnClickListener(onClickListener);
        animFlipck.setOnClickListener(onClickListener);
        animPYCb.setOnClickListener(onClickListener);
        animPY.setOnClickListener(onClickListener);
        animFZCb.setOnClickListener(onClickListener);
        animFZ.setOnClickListener(onClickListener);
        aaMinor.setOnClickListener(onClickListener);
        aaPlus.setOnClickListener(onClickListener);
        vSreenCb.setOnClickListener(onClickListener);
        vSreen.setOnClickListener(onClickListener);
        hSreenCb.setOnClickListener(onClickListener);
        hSreen.setOnClickListener(onClickListener);
        rlReadBrightness.setOnClickListener(onClickListener);
        brightnessBar.setOnClickListener(onClickListener);
        followSys.setOnClickListener(onClickListener);
        savePowCb.setOnClickListener(onClickListener);
        bgContainter.setOnClickListener(onClickListener);
        savePow.setOnClickListener(onClickListener);

    }

    private View.OnClickListener onClickListener = v -> {
        onMenuClick(v);
        changeFlip(v);
        changeScreenOr(v);
    };

    public void showBgView(List<View> views) {
        bgContainter.removeAllViews();
        for (View view : views) {
            bgContainter.addView(view);
        }
    }


//    @OnClick({R.id.tvBookReadToc, R.id.tvBookReadDownload, R.id.tvBookReadLD, R.id.tvBookReadSettings, R.id.ivBack})
    void onMenuClick(View view) {
        int i = view.getId();
        if (i == R.id.tvBookReadToc) {
            ChaptersActivity.startActivity(this, bookListsBean, SettingManager.getInstance().getScreenOrientation());

        } else if (i == R.id.tvBookReadDownload) {
        } else if (i == R.id.tvBookReadLD) {
            showMenu(rlReadBrightness);

        } else if (i == R.id.tvBookReadSettings) {
            showMenu(rlReadAaSet);

        } else if (i == R.id.ivBack) {
            finish();

        }
        else if (i == R.id.autoRead){
            autoRead();
        }
        else if (i == R.id.h1) {
            setHCheckBox(h1);
            setSpace(0.5f);

        } else if (i == R.id.h2) {
            setHCheckBox(h2);
            setSpace(0.6f);

        } else if (i == R.id.h3) {
            setHCheckBox(h3);
            setSpace(0.7f);
        } else if (i == R.id.h4) {
            setHCheckBox(h4);
            setSpace(0.8f);
        }
        else if (i == R.id.tvBookReadDownload){
            downloadBook();
        }
        else if (i == R.id.preChapter || i == R.id.nextChapter){
            gotoChapter(view);
        }
        else if (i == R.id.aaMinor || i == R.id.aaPlus){
            changeFontSize(view);
        }
        else if (i == R.id.savePowLayout){
            savePow();
        }
    }
    void autoRead() {
        mPageWidget.setAim(3);
        hideReadBar();
    }

    void setHCheckBox(CheckBox h) {
        h1.setChecked(false);
        h2.setChecked(false);
        h3.setChecked(false);
        h4.setChecked(false);
        h.setChecked(true);

    }

    void showMenu(View... view) {
        gone(mTvDownloadProgress, settingNight, chapterSelect, mLlBookReadBottom, mLlBookReadTop, rlReadAaSet, rlReadBrightness);
        visible(view);
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }


    private View decodeView;


    private ReadView mPageWidget;
    private IntentFilter intentFilter = new IntentFilter();

    BookListsBean bookListsBean;
    private String bookId;
    private boolean isFromSD = false;

    private int currentChapter = 1;
    private boolean startRead = false;

    private boolean isAutoLightness = false;


    private List<ChapterList.BookChapter> mChapterList = new ArrayList<>();


    public static final String INTENT_BEAN = "recommendBooksBean";
    public static final String INTENT_CHAPTER = "recommendCHAPTER";
    public static final String INTENT_SD = "isFromSD";

    public static void startActivity(Context context, BookListsBean bookListsBean) {
        startActivity(context, bookListsBean, false, 0);
    }

    public static void startActivity(Context context, BookListsBean bookListsBean, int currentChapter) {
        startActivity(context, bookListsBean, false, currentChapter);
    }

    public static void startActivity(Context context, BookDetail bookDetail) {
        BookListsBean bookListsBean = new BookListsBean();
        bookListsBean._id = bookDetail._id;
        bookListsBean.title = bookDetail.title;
        bookListsBean.author = bookDetail.author;
        bookListsBean.cover = bookDetail.cover;
        bookListsBean.lastChapter = bookDetail.lastChapter;
        bookListsBean.updated = bookDetail.updated;
        bookListsBean.sourceName = bookDetail.sourceName;
        bookListsBean.majorCate = bookDetail.majorCate;
        bookListsBean.minorCate = bookDetail.minorCate;
        bookListsBean.isSerial = bookDetail.isSerial;
        startActivity(context, bookListsBean, false, 0);
    }

    public static void startActivity(Context context, BookListsBean bookListsBean, boolean isFromSD, int currentChapter) {
        BuiduUtils.readBook(context, bookListsBean.title);
        context.startActivity(new Intent(context, ReadActivity.class)
                .putExtra(INTENT_BEAN, bookListsBean)
                .putExtra(INTENT_SD, isFromSD)
                .putExtra(INTENT_CHAPTER, currentChapter));
    }

    @Override
    protected void injectComponent() {
        bindView();
        ((XActivityComponent) getActivityComponent()).inject(this);
    }

    @Override
    protected int getLayoutId() {
        int type = SettingManager.getInstance().getScreenOrientation();
        switch (type) {
            case Constant.SCREEN_ORIENTATION_PORTRAIT:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return R.layout.activity_read;
            case Constant.SCREEN_ORIENTATION_LANDSCAPE:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                return R.layout.activity_read_h;
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        return R.layout.activity_read;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDatas();
        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        bookListsBean = (BookListsBean) getIntent().getSerializableExtra(INTENT_BEAN);
        bookId = bookListsBean._id;
        isFromSD = getIntent().getBooleanExtra(INTENT_SD, false);
        currentChapter = getIntent().getIntExtra(INTENT_CHAPTER, 0);
        startRead = false;
        readCurrentChapter();
        hideReadBar();
    }

    protected LoadingDialog newLoadingDialogs() {
        return LoadingDialog.getAppProgress(this, true, null);
    }

    class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (mPageWidget != null) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    int level = intent.getIntExtra("level", 0);
                    mPageWidget.setBattery(100 - level);
                } else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                    mPageWidget.setTime(sdf.format(new Date()));
                }
            }
        }
    }

    LoadingDialog appProgress;

    public void showAppProgress() {
        if (appProgress == null) {
            appProgress = newLoadingDialogs();
        }
        appProgress.show();
    }

    public void hideAppProgress() {
        if (appProgress != null) {
            appProgress.dismiss();
        }
    }

    void gotoReadChapter(int chapter) {
        currentChapter = chapter;
        startRead = false;
        readCurrentChapter();
    }

    public void initDatas() {
        bookListsBean = (BookListsBean) getIntent().getSerializableExtra(INTENT_BEAN);
        bookId = bookListsBean._id;
        isFromSD = getIntent().getBooleanExtra(INTENT_SD, false);
        currentChapter = getIntent().getIntExtra(INTENT_CHAPTER, 0);


        if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            String filePath = Uri.decode(getIntent().getDataString().replace("file://", ""));
            String fileName;
            if (filePath.lastIndexOf(".") > filePath.lastIndexOf("/")) {
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."));
            } else {
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            }

            CollectionsManager.getInstance().remove(fileName);
            // 转存
            File desc = FileUtils.createWifiTranfesFile(fileName);
            FileUtils.fileChannelCopy(new File(filePath), desc);
            // 建立
            bookListsBean = new BookListsBean();
//            bookListsBean.isFromSD = true;
            bookListsBean._id = fileName;
            bookListsBean.title = fileName;
            isFromSD = true;
        }
        RxBus.get().register(this);

        mTvBookReadTocTitle.setText(bookListsBean.title);

        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);

        CollectionsManager.getInstance().setRecentReadingTime(bookId);
//        Observable.timer(1000, TimeUnit.MILLISECONDS)
//                .subscribe(new Action1<Long>() {
//                    @Override
//                    public void call(Long aLong) {
//                        //延迟1秒刷新书架
//                        EventManager.refreshCollectionList();
//                    }
//                });
        presenter.getChapterLst(bookId);
    }


    void initView() {
        decodeView = (ViewGroup) findViewById(android.R.id.content);
        statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
        hideStatusBar();
        initPagerWidget();
        initBrightNessSet();
        initAAset();
        if (isFromSD) {
            ChapterList.BookChapter chapters = new ChapterList.BookChapter();
            chapters.title = bookListsBean.title;
            mChapterList.add(chapters);
            showChapterRead(null, currentChapter);
            mTvBookReadDownload.setVisibility(View.GONE);
            return;
        }
    }


    private void initPagerWidget() {
        showAppProgress();
        mPageWidget = new ReadView(this, bookId, mChapterList, new ReadListener());
        switch (SettingManager.getInstance().getFlipStyle()) {
            case 0:
                mPageWidget.setAim(0);
                animFlipckCb.setChecked(false);
                animPYCb.setChecked(false);
                animFZCb.setChecked(true);
                break;
            case 1:
                mPageWidget.setAim(1);
                animFlipckCb.setChecked(true);
                animPYCb.setChecked(false);
                animFZCb.setChecked(false);
                break;
            case 2:
                mPageWidget.setAim(2);
                animFlipckCb.setChecked(false);
                animPYCb.setChecked(true);
                animFZCb.setChecked(false);
        }

        mPageWidget.setFontSize(ScreenUtils.dpToPxInt(SettingManager.getInstance().getReadFontSize(bookId)));

        registerReceiver(receiver, intentFilter);
        if (SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false)) {
            mPageWidget.setTextColor(ContextCompat.getColor(this, R.color.chapter_content_night),
                    ContextCompat.getColor(this, R.color.chapter_title_night));
        }
        showTheme(SettingManager.getInstance().getReadTheme());
        flReadWidget.removeAllViews();
        flReadWidget.addView(mPageWidget);
        flReadWidget.bringToFront();

    }

    public void showBookToc(List<ChapterList.BookChapter> list) {
        mChapterList.clear();
        mChapterList.addAll(list);
        readCurrentChapter();
        initChapterBar();
    }

    ChapterDialog downloadDialog;

//    @OnClick(R.id.tvBookReadDownload)
    public void downloadBook() {
        gone(rlReadAaSet);
        if (downloadDialog == null) {
            downloadDialog = new ChapterDialog(this);
            downloadDialog.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int i = v.getId();
                    if (i == R.id.all) {
                        DownloadBookService.post(new DownloadQueue(bookListsBean.title, bookId, mChapterList, 1, mChapterList.size()));

                    } else if (i == R.id.fromNow) {
                        DownloadBookService.post(new DownloadQueue(bookListsBean.title, bookId, mChapterList, currentChapter + 1, mChapterList.size()));

                    } else if (i == R.id.cannel) {
                        downloadDialog.dismiss();

                    }
                }
            });
        }
        downloadDialog.show();
    }

//    @OnClick({R.id.preChapter, R.id.nextChapter})
    void gotoChapter(View v) {
        if (mChapterList == null && mChapterList.size() <= 0) {
            return;
        }
        if (v.getId() == R.id.preChapter) {
            currentChapter--;
        } else {
            currentChapter++;
        }
        currentChapter = currentChapter < 0 ? 0 : currentChapter;
        currentChapter = currentChapter > mChapterList.size() ? mChapterList.size() : currentChapter;
        seekbarChapter.setProgress(currentChapter);
        gotoReadChapter(currentChapter);
    }

    void initChapterBar() {
        seekbarChapter.setMax(mChapterList.size());
        seekbarChapter.setProgress(currentChapter);
        seekbarChapter.setOnSeekBarChangeListener(new SeekBarChangeListener());
    }

    public void readCurrentChapter() {
        if (CacheManager.getInstance().getChapterFile(bookId, currentChapter) != null || currentChapter == 0) {
            showChapterRead(null, currentChapter);
        } else {
            presenter.getChapterRead(mChapterList.get(currentChapter - 1).link, currentChapter);
        }
    }

    public synchronized void showChapterRead(Chapter data, int chapter) {
        if (data != null) {
            CacheManager.getInstance().saveChapterFile(bookId, chapter, data);
        }

        if (!startRead) {
            startRead = true;
            currentChapter = chapter;
            if (!mPageWidget.isPrepared) {
                mPageWidget.init(SettingManager.getInstance().getReadTheme(), currentChapter);
            } else {
                mPageWidget.jumpToChapter(currentChapter);
            }
            hideAppProgress();
        }
    }

    private ContentObserver Brightness = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            //LogUtils.d("BrightnessOnChange:" + ScreenUtils.getScreenBrightnessInt255());
            if (!ScreenUtils.isAutoBrightness(ReadActivity.this)) {
                brightnessBar.setProgress(ScreenUtils.getScreenBrightness());
            }
        }
    };

//    @OnClick({R.id.animFlipckCb, R.id.animFlipck, R.id.animPYCb, R.id.animPY, R.id.animFZCb, R.id.animFZ})
    void changeFlip(View v) {
        int i = v.getId();
        if (i == R.id.animFlipckCb || i == R.id.animFlipck) {
            animFlipckCb.setChecked(true);
            animPYCb.setChecked(false);
            animFZCb.setChecked(false);
            SettingManager.getInstance().saveFlipStyle(1);
            mPageWidget.setAim(1);

        } else if (i == R.id.animPYCb || i == R.id.animPY) {
            animFlipckCb.setChecked(false);
            animPYCb.setChecked(true);
            animFZCb.setChecked(false);
            SettingManager.getInstance().saveFlipStyle(2);
            mPageWidget.setAim(2);

        } else if (i == R.id.animFZCb || i == R.id.animFZ) {
            animFlipckCb.setChecked(false);
            animPYCb.setChecked(false);
            animFZCb.setChecked(true);
            SettingManager.getInstance().saveFlipStyle(0);
            mPageWidget.setAim(0);

        }
    }


//    @OnClick({R.id.vSreen, R.id.vSreenCb, R.id.hSreen, R.id.hSreenCb})
    void changeScreenOr(View v) {
        int i = v.getId();
        if (i == R.id.vSreen || i == R.id.vSreenCb) {
            vSreenCb.setChecked(true);
            hSreenCb.setChecked(false);
            SettingManager.getInstance().saveScreenOrientation(0);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        } else if (i == R.id.hSreen || i == R.id.hSreenCb) {
            vSreenCb.setChecked(false);
            hSreenCb.setChecked(true);
            SettingManager.getInstance().saveScreenOrientation(1);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }
    }


//    @OnClick({R.id.aaMinor, R.id.aaPlus})
    void changeFontSize(View v) {
        int size = SettingManager.getInstance().getReadFontSize(bookId);
        if (v.getId() == R.id.aaMinor) {
            size--;
        } else {
            size++;
        }
        size = size < 8 ? 8 : size;
        size = size > 40 ? 40 : size;
        SettingManager.getInstance().saveFontSize(bookId, size);
        mPageWidget.setFontSize(ScreenUtils.dpToPxInt(size));

    }

    void initAAset() {
        int type = SettingManager.getInstance().getScreenOrientation();
        switch (type) {
            case Constant.SCREEN_ORIENTATION_PORTRAIT:
                hSreenCb.setChecked(false);
                vSreenCb.setChecked(true);
                break;
            case Constant.SCREEN_ORIENTATION_LANDSCAPE:
                hSreenCb.setChecked(true);
                vSreenCb.setChecked(false);
                break;
        }
        settingNight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, true);
                    showTheme(ThemeManager.NIGHT);
                } else {
                    SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, false);
                    showTheme(SettingManager.getInstance().getReadTheme());
                }
            }
        });
    }

    void initBrightNessSet() {
        brightnessBar.setMax(100);
        brightnessBar.setOnSeekBarChangeListener(new SeekBarChangeListener());
        isAutoLightness = ScreenUtils.isAutoBrightness(this);

        this.getContentResolver().registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), true, Brightness);

        if (SettingManager.getInstance().isAutoBrightness()) {
            brightnessBar.setProgress(ScreenUtils.getScreenBrightness());
            startAutoLightness();
        } else {
            brightnessBar.setProgress(SettingManager.getInstance().getReadBrightness());
            stopAutoLightness();
        }

        followSys.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SettingManager.getInstance().saveAutoBrightness(isChecked);
                if (SettingManager.getInstance().isAutoBrightness()) {
                    startAutoLightness();
                } else {
                    stopAutoLightness();
                }
            }
        });
    }

//    @OnClick(R.id.savePowLayout)
    void savePow() {
        savePowCb.setChecked(!savePowCb.isChecked());
        if (savePowCb.isChecked()) {
            showTheme(ThemeManager.NIGHT);
            ScreenUtils.saveScreenBrightnessInt100(30, ReadActivity.this);
            brightnessBar.setProgress(30);
        } else {
            showTheme(SettingManager.getInstance().getReadTheme());
            if (SettingManager.getInstance().isAutoBrightness()) {
                brightnessBar.setProgress(ScreenUtils.getScreenBrightness());
                startAutoLightness();
            } else {
                brightnessBar.setProgress(SettingManager.getInstance().getReadBrightness());
                stopAutoLightness();
            }
        }
    }

    private void startAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(true);
        ScreenUtils.startAutoBrightness(ReadActivity.this);
        brightnessBar.setEnabled(false);
    }

    private void stopAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(false);
        ScreenUtils.stopAutoBrightness(ReadActivity.this);
        brightnessBar.setProgress((int) (ScreenUtils.getScreenBrightnessInt255() / 255.0F * 100));
        brightnessBar.setEnabled(true);
    }


    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (seekBar.getId() == seekbarChapter.getId() && fromUser) {
                gotoReadChapter(progress);
            } else if (seekBar.getId() == brightnessBar.getId() && fromUser
                    && !SettingManager.getInstance().isAutoBrightness()) { // 非自动调节模式下 才可调整屏幕亮度
                ScreenUtils.saveScreenBrightnessInt100(progress, ReadActivity.this);
                SettingManager.getInstance().saveReadBrightness(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    public void showTheme(int theme) {
        mPageWidget.setTheme(theme);
        mPageWidget.setTextColor(ThemeManager.getThemeTextColor(theme), ThemeManager.getThemeTextColor(theme));
    }

    public void setSpace(float space) {
        mPageWidget.setLetterSpacing(space);
    }

    private synchronized void hideReadBar() {
        gone(mTvDownloadProgress, settingNight, chapterSelect, mLlBookReadBottom, mLlBookReadTop, rlReadAaSet, rlReadBrightness);
        hideStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    }

    private synchronized void showReadBar() { // 显示工具栏
        visible(mTvDownloadProgress, mLlBookReadBottom, settingNight, chapterSelect, mLlBookReadTop);
        showStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    private synchronized void toggleReadBar() { // 切换工具栏 隐藏/显示 状态
        if (isVisible(mLlBookReadTop) || isVisible(chapterSelect) || isVisible(mLlBookReadBottom) ||
                isVisible(rlReadAaSet) || isVisible(rlReadBrightness)) {
            hideReadBar();
        } else {
            showReadBar();
        }
    }


    protected void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
        decodeView.setPadding(0, 0, 0, 0);
        if (statusBarView != null) {
            statusBarView.setBackgroundColor(Color.TRANSPARENT);
        }
    }

    protected void showStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
        decodeView.setPadding(0, DensityUtil.getStatusBarHeight(this), 0, 0);
        if (statusBarView != null) {
            statusBarView.setBackgroundColor(statusBarColor);
        }
    }


    private class ReadListener implements OnReadStateChangeListener {
        @Override
        public void onChapterChanged(int chapter) {
            Timber.i("onChapterChanged:" + chapter);
            currentChapter = chapter;
//            mTocListAdapter.setCurrentChapter(currentChapter);
            // 加载前一节 与 后三节
            for (int i = chapter - 1; i <= chapter + 3 && i <= mChapterList.size(); i++) {
                if (i > 0 && i != chapter
                        && CacheManager.getInstance().getChapterFile(bookId, i) == null) {
                    presenter.getChapterRead(mChapterList.get(i - 1).link, i);
                }
            }
            mTvDownloadProgress.setText("来源于：追书网");
            mTvDownloadProgress.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    presenter.openBrowser(ReadActivity.this, mChapterList.get(chapter - 1).link);
                }
            });
        }

        @Override
        public void onPageChanged(int chapter, int page) {
            Timber.i("onPageChanged:" + chapter + "-" + page);
        }

        @Override
        public void onLoadChapterFailure(int chapter) {
            Timber.i("onLoadChapterFailure:" + chapter);
            startRead = false;
            if (CacheManager.getInstance().getChapterFile(bookId, chapter) == null)
                presenter.getChapterRead(mChapterList.get(chapter - 1).link, chapter);
        }

        @Override
        public void onCenterClick() {
            Timber.i("onCenterClick");
            toggleReadBar();
        }

        @Override
        public void onFlip() {
            hideReadBar();
        }

        @Override
        public void onChapterEnd() {
            presenter.chapterEnd();
        }

        @Override
        public Bitmap getEndAdBitmap(int remain) {
            return presenter.getEndAdBitmap(remain);
        }

        @Override
        public Bitmap getEndAdBitmapSmall() {
            return presenter.getEndAdBitmapSmall();
        }

        @Override
        public Bitmap getStartAdBitmap() {
            return presenter.getStartAdBitmap();
        }

        @Override
        public void onClickSource(String link) {
            presenter.openBrowser(ReadActivity.this, link);
        }

        @Override
        public void onClickDescla() {
            AgreementActivity.startActivity(ReadActivity.this);
        }
    }


    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            Timber.e("Receiver not registered");
        }

        this.getContentResolver().unregisterContentObserver(Brightness);

        if (isAutoLightness) {
            ScreenUtils.startAutoBrightness(ReadActivity.this);
        } else {
            ScreenUtils.stopAutoBrightness(ReadActivity.this);
        }
        super.onDestroy();
    }

    protected void gone(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    protected void visible(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.VISIBLE);
                }
            }
        }

    }

    protected boolean isVisible(View view) {
        return view.getVisibility() == View.VISIBLE;
    }

}
